package cn.com.customer.manager.ui.customer.customerList

import android.content.Intent
import android.view.View
import cn.com.customer.manager.Constants
import cn.com.customer.manager.R
import cn.com.customer.manager.adapter.CustomerAdapter
import cn.com.customer.manager.base.BaseFragment
import cn.com.customer.manager.bean.StickyItem
import cn.com.customer.manager.ui.customer.add.AddCustomerActivity
import cn.com.customer.manager.ui.customer.detail.CustomerDetailActivity
import com.google.android.material.tabs.TabLayout
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.actionbar.TitleBar
import com.xuexiang.xui.widget.searchview.MaterialSearchView
import com.xuexiang.xui.widget.searchview.MaterialSearchView.SearchViewListener
import com.xuexiang.xutil.display.BarUtils
import kotlinx.android.synthetic.main.fragment_customer.*


/**
 * 客户  //TODO 添加刷新和加载更多
 */

class CustomerFragment : BaseFragment(), CustomerContract.View {
    private lateinit var mAdapter: CustomerAdapter
    private var params: MutableMap<String, String> = mutableMapOf()
    private var page = 1
    private var type = 0
    private var mData: MutableList<StickyItem> = mutableListOf()
    private var mSearchData: MutableList<StickyItem> = mutableListOf()
    private var mRealSearchData: MutableList<StickyItem> = mutableListOf()
    private var mPresenter: CustomerContract.Presenter = CustomerPresenter(this)
    private var mType = 1
    private var mSearchText = "";
    override fun getLayoutId(): Int = R.layout.fragment_customer

    override fun initView() {
        cus_title.addAction(object : TitleBar.ImageAction(R.drawable.ic_action_search) {
            override fun performAction(view: View?) {
                cus_search_view.showSearch()
            }

        })
        iv_add_customer.setOnClickListener { startActivity(Intent(activity, AddCustomerActivity::class.java)) }
        BarUtils.addMarginTopEqualStatusBarHeight(cus_search_view)
        cus_search_view.setVoiceSearch(false)
        cus_search_view.setEllipsize(true)
        cus_search_view.setBackgroundResource(R.color.bg_color)

        cus_search_view.setOnQueryTextListener(object : MaterialSearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                onQueryResult(query)
                mSearchText = ""
                return false
            }

            override fun onQueryTextChange(newText: String): Boolean { //Do some magic
                mSearchText = newText
                if(mSearchText!=null){
                    requestData()
                }
                return false
            }
        })
        cus_search_view.setOnSearchViewListener(object : SearchViewListener {
            override fun onSearchViewShown() { //Do some magic
                mType = 0
            }

            override fun onSearchViewClosed() {
                mType = 1//Do some magic
                mSearchText = ""
            }
        })
        cus_search_view.setSubmitOnClick(true)
        recycler_view.isNestedScrollingEnabled = false
        WidgetUtils.initRecyclerView(recycler_view)
        recycler_view.adapter = CustomerAdapter().also {
            mAdapter = it
        }
        mAdapter.refresh(mData)
        mAdapter.setOnItemClickListener { _, item, _ ->
            if (!item.isHeadSticky) {
                startActivity(Intent(activity, CustomerDetailActivity::class.java).putExtra("customerId", item.customerInfo.id))
            }
        }
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                type = p0?.let {
                    it.position
                }!!
                page = 1
                requestData()
            }

        })
        requestData()
    }

    private fun requestData() {
        params["pageNo"] = page.toString()
        params["pageSize"] = Constants.PAGE_SIZE.toString()
        params["name"] = mSearchText
        params["telephone"] = ""
        mPresenter.getData(params)
    }

    override fun onDestroyView() {
//        sticky_container.recycle()
        if (cus_search_view.isSearchOpen) {
            cus_search_view.closeSearch()
        }
        super.onDestroyView()
    }

    override fun setData(privateCustomers: List<StickyItem>, publicCustomers: List<StickyItem>) {
        if (mType == 1) {
            initListData(privateCustomers, publicCustomers)
        } else {
            initSearchData(privateCustomers, publicCustomers)
        }

    }

    private fun onQueryResult(query: String) {
      var item=mRealSearchData[suggestions.indexOf(query)]
        startActivity(Intent(activity, CustomerDetailActivity::class.java).putExtra("customerId", item.customerInfo.id))
    }

    var suggestions: MutableList<String> = mutableListOf()
    private fun initSearchData(privateCustomers: List<StickyItem>, publicCustomers: List<StickyItem>) {
        mSearchData.clear()
        suggestions.clear()
        mRealSearchData.clear()
        mSearchData.addAll(privateCustomers)
        mSearchData.addAll(publicCustomers)
        mSearchData.forEach {
            if (!it.isHeadSticky) {
                suggestions.add(it.customerInfo.name)
                mRealSearchData.add(it)
            }
        }
        cus_search_view.setSuggestions(suggestions.toTypedArray())
    }

    private fun initListData(privateCustomers: List<StickyItem>, publicCustomers: List<StickyItem>) {
        mData.clear()
        when (type) {
            0 -> {
                mData = privateCustomers as MutableList<StickyItem>
            }
            1 -> {
                mData = publicCustomers as MutableList<StickyItem>
            }

        }
        if (page == 1) {
            mAdapter.refresh(mData)
        } else {
            mAdapter.loadMore(mData)
        }
    }

    override fun belongPublicSuccess() {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun setPresenter(presenter: CustomerContract.Presenter) {
        mPresenter = presenter
    }

}